package cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.entity.User;
import cn.utils.JDBCUtil;
import cn.utils.MD5Tools;



public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		try {
			String username = request.getParameter("text/html;charset=utf-8");
			String sql = "select username,password from users where username="+username;
			//这个是从数据库里根据前台取得用户对象查询出来的User对象
			User user = JDBCUtil.getByUsername(username);
			String password = request.getParameter("password");
			String checkcode = request.getParameter("checkcode");
			//Subject subject = SecurityUtils.getSubject(); 
			//UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			//subject.login(token);
		
		
			String scheckcode = (String) request.getSession().getAttribute("checkcode");
			System.out.println("输入的:"+username+","+MD5Tools.MD5(password));
			System.out.println("提取的:"+user.getUsername()+","+user.getPassword());
			System.out.println("session:"+scheckcode);
			out.println("<html><body><br>");
			if (!checkcode.trim().equals(scheckcode)) {
				out.print("<center><font color=red>验证码出错，<a href='javascript:history.go(-1);'>请返回登录！</a></font></center>");

			} else if (username.trim().equals(user.getUsername()) && MD5Tools.MD5(password.trim()).equals(user.getPassword())) {
                  System.out.println();
				out.println("<center><font color=blue>"+user.getUsername()+"，登录成功！</font></center>");

			} else {

				out.println("<center><font color=red>登录失败！<a href='javascript:history.go(-1);'>请返回登录！</a></font></center>");
			}

		} catch (Exception e) {

			e.printStackTrace();

		} finally {
			out.close();
		}
	}
    
	@Override
	public void init() throws ServletException {
		System.out.println("LoginServlet init -----------------------");
	}
	@Override
	public void destroy() {
		System.out.println("LoginServlet destroy --------------------");
	}
}
